package com.ego.product.web;

import com.ego.common.util.Result;
import com.ego.product.service.CartService;
import com.ego.common.vo.product.CartUpdateVo;
import com.ego.common.vo.product.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.ExecutionException;


/**
 * @program: ego
 * @description: 购物车
 * @author: KamTang
 * @create: 2022-12-14 16:23
 **/
@Controller
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 进入购物车列表
     */
    @GetMapping("/")
    public String page(Model model) throws ExecutionException, InterruptedException {
        CartVo cartVo = cartService.get(null);
        log.info("cart => {}", cartVo);
        model.addAttribute("cart", cartVo);
        return "cart";
    }

    /**
     * 将商品添加到购物车中
     */
    @PostMapping("/add-to-cart")
    @ResponseBody
    public Result addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("count") Integer count,
                            Model model) throws ExecutionException, InterruptedException {
        CartVo.CartItem cartItem = cartService.addToCart(skuId, count);
        model.addAttribute("cartItem", cartItem);
        return Result.ok();
    }

    /**
     * 更新购物项中的数据
     */
    @PostMapping("/update")
    @ResponseBody
    public Result update(@Valid @RequestBody CartUpdateVo updateVo) {
        try {
            cartService.update(updateVo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 移除购物项
     */
    @PostMapping("/delete/{skuId}/{promotion}")
    @ResponseBody
    public Result delete(@PathVariable("skuId") Long skuId, @PathVariable("promotion") Integer promotion) {
        cartService.delete(skuId, promotion);
        return Result.ok();
    }

    /**
     * 获取当前用户的购物项
     */
    @GetMapping("/getItem")
    @ResponseBody
    public Result getCurrentUserCartItem(@RequestParam("memberId") Long memberId) {
        List<CartVo.CartItem> cartItems = cartService.getCurrentUserCartItem(memberId);
        return Result.ok().put("cartItems", cartItems);
    }
}
